package servlet;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.MemberCardStatistics;

import model.Member;

import factory.DaoFactory;

/**
 * Servlet implementation class MemberCardStatisticsServlet
 */
@WebServlet("/MemberCardStatisticsServlet")
public class MemberCardStatisticsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MemberCardStatisticsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int nonActivated = 0;
		int activated = 0;
		int stopped = 0;
		int cancelled = 0;
		List<Member> list = DaoFactory.getMemberDao().findAll();
		for (int i = 0; i < list.size(); i++) {
			Member member = list.get(i);
			if (member.getBalance() == -1) {
				nonActivated++;
			} else {
				if (Calendar.getInstance().getTimeInMillis() - member.getLastRecharge().getTime() > 2*365*24*3600000L) {
					cancelled++;
				} else if (Calendar.getInstance().getTimeInMillis() - member.getLastRecharge().getTime() > 365*24*3600000L) {
					stopped++;
				} else {
					activated++;
				}
			}
		}
		MemberCardStatistics statistics = new MemberCardStatistics(nonActivated, activated, stopped, cancelled);
		request.setAttribute("statistics", statistics);
		
		String address ="/jsp/MemberCardStatistics.jsp";
		if ((activated + 0.0) / (nonActivated + activated + stopped + cancelled) < 0.7) {
			address += "?exception=true";
		}
		
		RequestDispatcher dispatcher =request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
